import { defineStore } from 'pinia'
import { nextTick, ref, computed, readonly } from 'vue'
import { useRouter as vueUseRouter, Router } from 'vue-router'
import { sessionStorage } from '../utils/storage'
import { normalizePath } from '../utils/pathHelper'
import { useTitleStore } from './title'
import { getPathTitle } from '../utils/titleObserver'

export interface TabItem {
  name?: string
  path: string
  title?: string
  icon?: string
  keepAlive?: boolean
  fixed?: boolean
  isMicroApp?: boolean
  microAppName?: string
  suffix?: string
  menuId?: string | number
  permission?: string
}

// 创建一个全局路由实例引用
let router: Router

export const useTabStore = defineStore('tab', () => {
  const tabs = ref<TabItem[]>(sessionStorage.get('tabs', []) as TabItem[] || [])
  const activeTab = ref<string>(sessionStorage.get('activeTab', '') as string || '')
  const reloading = ref<boolean>(false)
  
  // 确保在组件内调用时获取路由实例
  try {
    router = vueUseRouter()
  } catch (e) {
    // 可能不在Vue组件内调用
    console.warn('Router instance not available, navigation may not work')
  }

  const activeIndex = computed(() => {
    return tabs.value.findIndex(item => normalizePath(item.path) === normalizePath(activeTab.value))
  })

  const keepAliveNames = computed(() => {
    return tabs.value.filter(item => item.keepAlive).map(item => item.name || '')
  })

  const setActiveTab = async (path: string) => {
    await nextTick()
    activeTab.value = normalizePath(path)
    sessionStorage.set('activeTab', activeTab.value)
  }

  const setTabs = (newTabs: TabItem[]) => {
    tabs.value = newTabs
    sessionStorage.set('tabs', tabs.value)
  }

  const addTab = (tab: TabItem = {} as TabItem) => {
    const normPath = normalizePath(tab.path)
    const findIndex = tabs.value.findIndex(item => normalizePath(item.path) === normPath)
    
    // 获取最新的title
    const titleStore = useTitleStore()
    const currentTitle = titleStore.getCurrentTitle()
    
    // 检查是否有该路径的缓存标题
    const cachedTitle = getPathTitle(normPath)
    
    // 优先使用缓存标题，其次是当前title，最后是tab自带的title
    const finalTitle = cachedTitle || currentTitle || tab.title || ''
    
    // 如果tab已存在，更新title
    if (findIndex !== -1) {
      const existingTab = tabs.value[findIndex]
      // 只有当标题不同时才更新，避免不必要的更新
      if (existingTab.title !== finalTitle) {
        tabs.value.splice(findIndex, 1, { 
          ...tab, 
          path: normPath,
          title: finalTitle
        })
        setTabs([...tabs.value])
      }
    } else {
      // 新建tab，使用当前title
      setTabs([...tabs.value, { 
        ...tab, 
        path: normPath,
        title: finalTitle
      }])
      
      // 确保在标题映射中保存标题
      if (finalTitle && typeof window !== 'undefined') {
        try {
          // 动态导入，避免循环依赖
          import('../utils/titleObserver').then(({ setPathTitle }) => {
            setPathTitle(normPath, finalTitle)
          })
        } catch (e) {
          console.error('[TabStore] Failed to set path title:', e)
        }
      }
    }
    setActiveTab(normPath)
  }

  // 更新当前激活tab的title
  const updateActiveTabTitle = () => {
    const titleStore = useTitleStore()
    const currentTitle = titleStore.getCurrentTitle()
    
    if (currentTitle && activeTab.value) {
      const activeTabItem = tabs.value.find(tab => normalizePath(tab.path) === normalizePath(activeTab.value))
      if (activeTabItem && activeTabItem.title !== currentTitle) {
        activeTabItem.title = currentTitle
        setTabs([...tabs.value])
      }
    }
  }

  // 更新指定路径tab的title
  const updateTabTitle = (path: string, newTitle: string) => {
    const normPath = normalizePath(path)
    const tabToUpdate = tabs.value.find(tab => normalizePath(tab.path) === normPath)
    
    if (tabToUpdate && tabToUpdate.title !== newTitle) {
      tabToUpdate.title = newTitle
      setTabs([...tabs.value])
    }
  }

  const reloadTab = async (path: string, keepAlive?: boolean) => {
    const normPath = normalizePath(path)
    const findItem = tabs.value.find(item => normalizePath(item.path) === normPath)
    if (!findItem) return
    
    if (keepAlive) findItem.keepAlive = false
    reloading.value = true
    await nextTick()
    reloading.value = false
    findItem.keepAlive = !!keepAlive
  }

  const removeTab = async (path: string) => {
    // 确保router实例存在
    if (!router) {
      try {
        router = vueUseRouter()
      } catch (e) {
        console.error('Router instance not available for navigation')
        return
      }
    }
    
    const normPath = normalizePath(path)
    const tabToRemove = tabs.value.find(tab => normalizePath(tab.path) === normPath)
    if (tabToRemove?.fixed) return
    
    // 找出当前标签在数组中的索引
    const currentIndex = tabs.value.findIndex(tab => normalizePath(tab.path) === normPath)
    
    // 如果关闭的是当前激活的标签，需要先确定跳转目标
    if (normPath === activeTab.value) {
      // 在移除前确定要跳转的标签
      let targetTab: TabItem | undefined
      
      // 存储一份副本用于确定跳转目标
      const currentTabs = [...tabs.value]
      
      if (currentIndex > 0) {
        // 如果不是第一个标签，选择前一个
        targetTab = currentTabs[currentIndex - 1]
      } else if (currentTabs.length > 1) {
        // 如果是第一个标签，选择第二个标签（关闭后会变成第一个）
        targetTab = currentTabs[1]
      }
      
      // 移除标签
      setTabs(tabs.value.filter(tab => normalizePath(tab.path) !== normPath))
      
      // 执行跳转
      if (targetTab && targetTab.path) {
        router.push(targetTab.path)
      } else {
        // 如果没有可跳转的标签，跳转到首页
        router.push('/')
      }
    } else {
      // 如果关闭的不是当前激活标签，直接移除
      setTabs(tabs.value.filter(tab => normalizePath(tab.path) !== normPath))
    }
  }

  const removeOther = (curPath: string = activeTab.value) => {
    // 确保router实例存在
    if (!router) {
      try {
        router = vueUseRouter()
      } catch (e) {
        console.error('Router instance not available for navigation')
        return
      }
    }
    
    const normPath = normalizePath(curPath)
    
    // 在修改前先确定跳转目标
    let targetTab: TabItem | undefined
    
    // 找到要保留的标签
    const remainingTabs = tabs.value.filter(tab => normalizePath(tab.path) === normPath || tab.fixed)
    
    // 如果当前激活的标签将被移除，需要选择一个新的目标
    if (normPath !== activeTab.value && !remainingTabs.find(tab => normalizePath(tab.path) === activeTab.value)) {
      // 优先选择传入的当前路径对应的标签
      targetTab = tabs.value.find(tab => normalizePath(tab.path) === normPath)
      // 如果没有，则选择第一个固定标签
      if (!targetTab) {
        targetTab = remainingTabs[0]
      }
    }
    
    // 应用标签过滤
    setTabs(remainingTabs)
    
    // 如果需要跳转，执行路由跳转
    if (targetTab && targetTab.path) {
      router.push(targetTab.path)
    } else if (!remainingTabs.find(item => normalizePath(item.path) === activeTab.value)) {
      // 如果当前激活标签被移除了，且没有找到目标标签，跳转到首页
      router.push('/')
    }
  }

  const removeLeft = (curPath: string) => {
    // 确保router实例存在
    if (!router) {
      try {
        router = vueUseRouter()
      } catch (e) {
        console.error('Router instance not available for navigation')
        return
      }
    }
    
    const normPath = normalizePath(curPath)
    const curIndex = tabs.value.findIndex(item => normalizePath(item.path) === normPath)
    
    // 在修改前先确定跳转目标
    let targetTab: TabItem | undefined
    
    // 保留当前索引及右侧的标签，以及固定标签
    const remainingTabs = tabs.value.filter((item, index) => index >= curIndex || item.fixed)
    
    // 如果当前激活的标签将被移除，需要选择一个新的目标
    if (!remainingTabs.find(item => normalizePath(item.path) === activeTab.value)) {
      // 优先选择固定标签
      targetTab = remainingTabs.find(tab => tab.fixed)
      // 其次选择当前指定的标签
      if (!targetTab) {
        targetTab = tabs.value.find(tab => normalizePath(tab.path) === normPath)
      }
      // 最后选择任意一个剩余标签
      if (!targetTab && remainingTabs.length > 0) {
        targetTab = remainingTabs[0]
      }
    }
    
    // 应用标签过滤
    setTabs(remainingTabs)
    
    // 如果需要跳转，执行路由跳转
    if (targetTab && targetTab.path) {
      router.push(targetTab.path)
    } else if (!remainingTabs.find(item => normalizePath(item.path) === activeTab.value)) {
      // 如果当前激活标签被移除了，且没有找到目标标签，跳转到首页
      router.push('/')
    }
  }

  const removeRight = (curPath: string) => {
    // 确保router实例存在
    if (!router) {
      try {
        router = vueUseRouter()
      } catch (e) {
        console.error('Router instance not available for navigation')
        return
      }
    }
    
    const normPath = normalizePath(curPath)
    const curIndex = tabs.value.findIndex(item => normalizePath(item.path) === normPath)
    
    // 在修改前先确定跳转目标
    let targetTab: TabItem | undefined
    
    // 保留当前索引及左侧的标签，以及固定标签
    const remainingTabs = tabs.value.filter((item, index) => index <= curIndex || item.fixed)
    
    // 如果当前激活的标签将被移除，需要选择一个新的目标
    if (!remainingTabs.find(item => normalizePath(item.path) === activeTab.value)) {
      // 优先选择当前指定的标签
      targetTab = tabs.value.find(tab => normalizePath(tab.path) === normPath)
      // 如果没有，选择一个固定标签
      if (!targetTab) {
        targetTab = remainingTabs.find(tab => tab.fixed)
      }
      // 最后选择最后一个标签
      if (!targetTab && remainingTabs.length > 0) {
        targetTab = remainingTabs[remainingTabs.length - 1]
      }
    }
    
    // 应用标签过滤
    setTabs(remainingTabs)
    
    // 如果需要跳转，执行路由跳转
    if (targetTab && targetTab.path) {
      router.push(targetTab.path)
    } else if (!remainingTabs.find(item => normalizePath(item.path) === activeTab.value)) {
      // 如果当前激活标签被移除了，且没有找到目标标签，跳转到首页
      router.push('/')
    }
  }

  const toggleFixTab = (path: string, isFixed: boolean) => {
    const normPath = normalizePath(path)
    const findIndex = tabs.value.findIndex(item => normalizePath(item.path) === normPath)
    if (findIndex !== -1) {
      tabs.value[findIndex].fixed = isFixed
      sessionStorage.set('tabs', tabs.value)
    }
  }

  const resetTabs = () => {
    tabs.value = []
    activeTab.value = ''
    reloading.value = false
    sessionStorage.remove('tabs')
    sessionStorage.remove('activeTab')
  }

  return {
    tabs: readonly(tabs),
    activeTab: readonly(activeTab),
    reloading: readonly(reloading),
    activeIndex,
    keepAliveNames,
    setActiveTab,
    setTabs,
    addTab,
    updateActiveTabTitle,
    reloadTab,
    removeTab,
    removeOther,
    removeLeft,
    removeRight,
    toggleFixTab,
    resetTabs,
    updateTabTitle
  }
}) 